<template>
  <div style="padding:16px;">
    <el-card shadow="never">
      <template #header>
        <div style="display:flex; align-items:center; justify-content:space-between;">
          <span style="font-size:16px; font-weight:600;">客户管理</span>
          <el-button type="primary" @click="handleAdd">新增客户</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="items"
        stripe
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" min-width="140" />
        <el-table-column prop="phone" label="电话" width="140" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="company" label="公司" min-width="160" />
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该客户？" @confirm="handleDelete(row.id)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div style="display:flex; align-items:center; justify-content:space-between; margin-top:16px;">
        <span style="font-size:12px; color:#666;">共 {{ total }} 条</span>
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="size"
          background
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="load"
          @current-change="load"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑客户' : '新增客户'" width="480px">
      <el-form ref="formRef" :model="form" label-width="80px" @submit.prevent>
        <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入姓名' }]">
          <el-input v-model="form.name" placeholder="客户姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="邮箱地址" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="居住地址" />
        </el-form-item>
        <el-form-item label="公司" prop="company">
          <el-input v-model="form.company" placeholder="公司名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '../api/http'
import type { PageResult, Customer } from '../types'

const items = ref<Customer[]>([])
const total = ref(0)
const page = ref(1)
const size = ref(20)
const loading = ref(false)

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive<Partial<Customer>>({})

async function load() {
  loading.value = true
  try {
    const res = await http.get<PageResult<Customer>>('/api/customers', {
      params: { page: page.value, size: size.value }
    })
    items.value = res.data.items
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

function handleAdd() {
  Object.assign(form, { name: '', phone: '', email: '', address: '', company: '' })
  dialogVisible.value = true
}

function handleEdit(row: Customer) {
  Object.assign(form, row)
  dialogVisible.value = true
}

async function handleSubmit() {
  await formRef.value.validate()
  const data = { ...form }
  try {
    if (data.id) {
      await http.put(`/api/customers/${data.id}`, data)
      ElMessage.success('客户更新成功')
    } else {
      await http.post('/api/customers', data)
      ElMessage.success('客户创建成功')
    }
    dialogVisible.value = false
    load()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '操作失败')
  }
}

async function handleDelete(id?: number) {
  if (!id) return
  try {
    await http.delete(`/api/customers/${id}`)
    ElMessage.success('客户已删除')
    load()
  } catch (e: any) {
    const msg = e?.response?.data?.message || e?.message || '删除失败'
    const status = e?.response?.status
    if (status === 400 && msg.includes('已被订单引用')) {
      await ElMessageBox.alert('该客户已被订单引用，无法删除', '无法删除', { type: 'warning', confirmButtonText: '知道了' })
    } else {
      ElMessage.error(msg)
    }
  }
}

onMounted(load)
</script>

<style scoped>
</style>